package com.zeng.createmd.restfulmodule.controller;

import com.zeng.createmd.restfulmodule.itemCache.ItemCache;
import com.zeng.createmd.restfulmodule.util.*;
import com.zeng.createmd.servicemodule.vo.DatabaseVo;
import com.zeng.createmd.servicemodule.vo.ItemVo;
import com.zeng.nicecommon.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping
@RestController
@ServerEndpoint("/cmd")
public class InitController {

    @Autowired
    ItemUtil itemUtil;

    @RequestMapping
    public Object initStatus() {
        Map<String, Boolean> returnMap = new HashMap<>();
        if (ItemCache.currentItem == null) {
            throw new RuntimeException("尚未选择项目");
        }
        ItemVo currentItem = ItemCache.currentItem;
        String artifactId = (String) currentItem.getInfo().get("artifactId");
        String groupId = (String) currentItem.getInfo().get("groupId");
        String path = currentItem.getPath();
        File file = new File(new File(path, "client"), artifactId);
        File vueProjectCode = new File(file, "src/project");
        returnMap.put("web-init", file.exists());
        returnMap.put("web-create", file.exists() && vueProjectCode.exists());
        String controllerPackage = groupId + "/" + artifactId + "/restfulmodule" + "/controller";
        controllerPackage = controllerPackage.replace("-", "").replace(".", "/");
        String restfulChildPath = String.format("server/%s/%s-restful/src/main/java/%s", artifactId, artifactId, controllerPackage);
        File restful = new File(path, restfulChildPath);
        returnMap.put("serve-create", restful.exists());
        ProjectUtil projectUtil = new ProjectUtil();
        String databaseInit = (String) projectUtil.getData().get("databaseInit");
        returnMap.put("database-create", databaseInit != null && databaseInit.equals("1"));
        return ResponseUtil.success("操作成功").addData("status", returnMap);
    }

    @RequestMapping
    public Object initVue() {
        VueUtil vueUtil = new VueUtil();
        vueUtil.createView();
        vueUtil.createConfig();
        return ResponseUtil.success("操作成功");
    }

    @RequestMapping
    public Object initServe() {
        Runtime runtime = Runtime.getRuntime();
        Process exec = null;
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        String maven_home = System.getenv("MAVEN_HOME");
        if (maven_home == null) {
            return ResponseUtil.badRequest("请设置maven的环境变量 MAVEN_HOME");
        }
        try {
            ItemVo currentItem = ItemCache.currentItem;
            if (currentItem == null) {
                throw new RuntimeException("没有选择项目");
            }
            String path = currentItem.getPath();
            File pomFile = new File(path, "server/" + currentItem.getInfo().get("artifactId").toString() + "/pom.xml");
            if (!pomFile.exists()) {
                return ResponseUtil.badRequest("前端结构未初始化");
            }
            StringBuilder commends = new StringBuilder("cmd.exe /c ");
            String pomRoot = pomFile.getAbsolutePath().split(":")[0] + ":";
            commends.append(pomRoot);
            commends.append(" && cd " + pomFile.getParentFile().getAbsolutePath());
            commends.append(" && dir && mvn clean && mvn com.zeng:create-entity-plugin:1.0-SNAPSHOT:create-class");

            exec = runtime.exec(commends.toString());
            inputStream = exec.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            String s = null;
            while ((s = bufferedReader.readLine()) != null) {
                WebSocketUtil.sendMessage(s);
            }
            exec.waitFor();
            if (exec.exitValue() != 0) {
                return ResponseUtil.serviceError("创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            CloseUtil.close(bufferedReader, inputStream);
        }
        return ResponseUtil.success("操作成功");
    }

    @RequestMapping
    public Object initDatabaseData() throws IOException, SQLException {
        DatabaseVo databaseVo = itemUtil.getDatabaseVo();
        if (databaseVo == null) {
            return ResponseUtil.badRequest("尚未初始化数据库");
        }
        ItemVo currentItem = ItemCache.currentItem;
        String artifactId = (String) currentItem.getInfo().get("artifactId");
        String path = currentItem.getPath();
        PropertyUtil.createDbProperty(databaseVo, new File(path, String.format("server/%s/%s-restful/src/main/resources/application-db.properties", artifactId, artifactId)));
        InitDatabaseDataUtil.initData(databaseVo);
        InitDatabaseDataUtil.initDataForMenu(databaseVo);
        ProjectUtil projectUtil = new ProjectUtil();
        projectUtil.getData().put("databaseInit", "1");
        projectUtil.init();
        return ResponseUtil.success("操作成功");
    }

//
//    public static void main(String[] args) {
//
//        String maven_home = System.getenv("MAVEN_HOME");
//        if (maven_home == null) {
//            return;
//        }
//        System.out.println(maven_home);
//        InvocationRequest request = new DefaultInvocationRequest();
//
//        request.setPomFile(new File("C:\\Users\\51399\\Desktop\\template\\com.zeng.md-test2\\server\\md-test2\\pom.xml"));
//        request.setGoals(Collections.singletonList("com.zeng:create-entity-plugin:1.0-SNAPSHOT:create-class"));
//        Invoker invoker = new DefaultInvoker();
//        PrintStream out = null;
//        try {
//             out = new PrintStream(new FileOutputStream("C:\\Users\\51399\\Desktop\\template\\test2.txt"));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        invoker.setMavenHome(new File("D:\\environment\\maven\\apache-maven-3.6.0"));
//        invoker.setLogger(new PrintStreamLogger(out, 5));
//        try {
//            InvocationResult execute = invoker.execute(request);
//        } catch (MavenInvocationException e) {
//            e.printStackTrace();
//        }
//    }

    @OnOpen
    public void openSession(Session session) {
        WebSocketUtil.setSession(session);
    }

    @OnClose
    public void closeSession() {
        WebSocketUtil.closeSession();
    }

}
